/**
 * 敏感词管理 Store
 */
import { defineStore } from 'pinia'
import api from '@/api'

export const useSensitiveWordStore = defineStore('sensitiveWord', {
  state: () => ({
    // 敏感词数据
    keywords: [],
    categories: ['不文明词语', '政治敏感', '违法违规', '商业敏感', '歧视言论', '网络暴力', '医疗违规'],
    
    // 数据库配置
    databases: [],
    currentDatabase: null,
    
    // 检查任务
    currentTask: null,
    taskHistory: [],
    checkResults: [],
    
    // 系统配置
    config: {
      batchSize: 1000,
      concurrency: 3,
      timeout: 30,
      caseSensitive: false,
      wholeWordOnly: false,
      useReadReplica: true,
      maxContentLength: 1000,
      contextLength: 100
    },
    
    // UI状态
    loading: false,
    checking: false,
    progress: {
      percentage: 0,
      message: '',
      checkedTables: 0,
      totalTables: 0,
      foundIssues: 0,
      elapsedTime: 0
    }
  }),

  getters: {
    // 按分类分组的敏感词
    keywordsByCategory: (state) => {
      const grouped = {}
      state.categories.forEach(category => {
        grouped[category] = state.keywords.filter(k => k.category === category)
      })
      return grouped
    },

    // 敏感词总数
    totalKeywords: (state) => state.keywords.length,

    // 检查结果统计
    resultStats: (state) => {
      if (!state.checkResults.length) return {}
      
      const stats = {
        total: state.checkResults.length,
        byCategory: {},
        byTable: {},
        uniqueTables: new Set(),
        uniqueCategories: new Set()
      }
      
      state.checkResults.forEach(result => {
        // 按分类统计
        if (!stats.byCategory[result.category]) {
          stats.byCategory[result.category] = 0
        }
        stats.byCategory[result.category]++
        
        // 按表统计
        if (!stats.byTable[result.tableName]) {
          stats.byTable[result.tableName] = 0
        }
        stats.byTable[result.tableName]++
        
        stats.uniqueTables.add(result.tableName)
        stats.uniqueCategories.add(result.category)
      })
      
      return {
        ...stats,
        uniqueTables: Array.from(stats.uniqueTables),
        uniqueCategories: Array.from(stats.uniqueCategories)
      }
    },

    // 当前任务状态
    taskStatus: (state) => {
      if (!state.currentTask) return 'idle'
      return state.currentTask.status || 'idle'
    }
  },

  actions: {
    // 加载敏感词
    async loadKeywords() {
      try {
        this.loading = true
        const response = await api.sensitiveWord.getKeywords()
        this.keywords = response.data || []
      } catch (error) {
        console.error('加载敏感词失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 添加敏感词
    async addKeyword(keyword) {
      try {
        const response = await api.sensitiveWord.addKeyword(keyword)
        this.keywords.push(response.data)
        return response.data
      } catch (error) {
        console.error('添加敏感词失败:', error)
        throw error
      }
    },

    // 更新敏感词
    async updateKeyword(id, keyword) {
      try {
        const response = await api.sensitiveWord.updateKeyword(id, keyword)
        const index = this.keywords.findIndex(k => k.id === id)
        if (index !== -1) {
          this.keywords[index] = response.data
        }
        return response.data
      } catch (error) {
        console.error('更新敏感词失败:', error)
        throw error
      }
    },

    // 删除敏感词
    async deleteKeyword(id) {
      try {
        await api.sensitiveWord.deleteKeyword(id)
        this.keywords = this.keywords.filter(k => k.id !== id)
      } catch (error) {
        console.error('删除敏感词失败:', error)
        throw error
      }
    },

    // 批量导入敏感词
    async batchImportKeywords(file) {
      try {
        const response = await api.sensitiveWord.batchImport(file)
        await this.loadKeywords() // 重新加载
        return response.data
      } catch (error) {
        console.error('批量导入失败:', error)
        throw error
      }
    },

    // 加载数据库列表
    async loadDatabases() {
      try {
        const response = await api.database.getDatabases()
        this.databases = response.data || []
      } catch (error) {
        console.error('加载数据库列表失败:', error)
        throw error
      }
    },

    // 选择数据库
    async selectDatabase(databaseId) {
      try {
        const database = this.databases.find(db => db.id === databaseId)
        if (database) {
          this.currentDatabase = database
          // 加载表列表
          const response = await api.database.getTables(databaseId)
          this.currentDatabase.tables = response.data || []
        }
      } catch (error) {
        console.error('选择数据库失败:', error)
        throw error
      }
    },

    // 开始检查
    async startCheck(config) {
      try {
        this.checking = true
        this.progress = {
          percentage: 0,
          message: '准备开始检查...',
          checkedTables: 0,
          totalTables: 0,
          foundIssues: 0,
          elapsedTime: 0
        }
        
        const response = await api.checkTask.startCheck(config)
        this.currentTask = response.data
        
        // 开始轮询进度
        this.pollProgress(this.currentTask.taskId)
        
        return this.currentTask
      } catch (error) {
        this.checking = false
        console.error('开始检查失败:', error)
        throw error
      }
    },

    // 轮询检查进度
    async pollProgress(taskId) {
      const poll = async () => {
        try {
          const response = await api.checkTask.getProgress(taskId)
          const progress = response.data
          
          this.progress = {
            percentage: progress.percentage,
            message: progress.message,
            checkedTables: progress.checkedTables,
            totalTables: progress.totalTables,
            foundIssues: progress.foundIssues,
            elapsedTime: progress.elapsedTime
          }
          
          if (progress.status === 'completed') {
            this.checking = false
            this.currentTask.status = 'completed'
            
            // 加载结果
            await this.loadResults(taskId)
            
            return true // 停止轮询
          } else if (progress.status === 'failed') {
            this.checking = false
            this.currentTask.status = 'failed'
            this.currentTask.error = progress.error
            
            return true // 停止轮询
          }
          
          return false // 继续轮询
        } catch (error) {
          console.error('获取进度失败:', error)
          return false
        }
      }
      
      // 开始轮询
      const pollInterval = setInterval(async () => {
        const shouldStop = await poll()
        if (shouldStop) {
          clearInterval(pollInterval)
        }
      }, 2000)
      
      // 设置超时
      setTimeout(() => {
        clearInterval(pollInterval)
        if (this.checking) {
          this.checking = false
          console.error('检查超时')
        }
      }, this.config.timeout * 60 * 1000)
    },

    // 加载检查结果
    async loadResults(taskId) {
      try {
        const response = await api.result.getResults(taskId)
        this.checkResults = response.data || []
      } catch (error) {
        console.error('加载结果失败:', error)
        throw error
      }
    },

    // 停止检查
    async stopCheck(taskId) {
      try {
        await api.checkTask.stopTask(taskId)
        this.checking = false
        if (this.currentTask && this.currentTask.taskId === taskId) {
          this.currentTask.status = 'stopped'
        }
      } catch (error) {
        console.error('停止检查失败:', error)
        throw error
      }
    },

    // 加载任务历史
    async loadTaskHistory() {
      try {
        const response = await api.checkTask.getTasks()
        this.taskHistory = response.data || []
      } catch (error) {
        console.error('加载任务历史失败:', error)
        throw error
      }
    },

    // 更新配置
    updateConfig(newConfig) {
      this.config = { ...this.config, ...newConfig }
    },

    // 清空结果
    clearResults() {
      this.checkResults = []
      this.currentTask = null
      this.progress = {
        percentage: 0,
        message: '',
        checkedTables: 0,
        totalTables: 0,
        foundIssues: 0,
        elapsedTime: 0
      }
    },

    // 重置状态
    reset() {
      this.checking = false
      this.loading = false
      this.clearResults()
    }
  }
})
